package com.example.study.test.suanfa;

import java.util.HashMap;

/**
 * @author: nannan
 * @date: 2020/11/23 10:49 下午
 * @description:
 */
public class ShuZuQiuHe {
    public static void main(String[] args) throws Exception {
        int[] array = {1,3,6,8,9};
        int target = 7;
        int[] result = sum1(array, target);
        for (int i : result) {
            System.out.println(i);
        }
    }

    /**
     * @description: 利用map求和 key值为目标值与当前元素的差
     * @author: nannan
     * @date: 2020/11/23 11:02 下午
     * @param array:
     * @param target:
     * @return: int[]
     */
    public static int[] sum1(int[] array, int target) throws Exception {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            if (map.containsKey(target - array[i])) {
                return new int[]{map.get(target - array[i]), i};
            }
            map.put(array[i], i);
        }
        throw new Exception("数组中没有和为结果的值");
    }
}
